package de.hska.reka.websockets.client;

import java.lang.reflect.Method;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.xlightweb.IWebSocketConnection;
import org.xlightweb.TextMessage;

import de.hska.reka.websockets.ICallbackHandler;
import de.hska.reka.websockets.Parser.JsonRPCParser;
import de.hska.reka.websockets.Parser.JsonRpcPackage;
import de.hska.reka.websockets.ResponseHandling.ResponseHandler;
import de.hska.reka.websockets.ResponseHandling.ThreadID;

@Component
public class OneToOneInvokationHandler implements ICallbackHandler {
	private JsonRPCParser jsonRPCParser = new JsonRPCParser();
	private IWebSocketConnection connection;

	@Autowired
	private ResponseHandler responseHandler;

	public ResponseHandler getResponseHandler() {
		return responseHandler;
	}

	public void setConnection(IWebSocketConnection connection) {
		this.connection = connection;
	}

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {

		JsonRpcPackage rpcPackage = new JsonRpcPackage();
		rpcPackage.setMethod(method.getDeclaringClass().getCanonicalName()
				+ "." + method.getName());
		rpcPackage.setParams(args);
		rpcPackage.setId(UUID.randomUUID().toString());
		this.responseHandler.registerThread(new ThreadID(rpcPackage.getId()));
		connection.writeMessage(new TextMessage(this.jsonRPCParser
				.serialize(rpcPackage)));
		return responseHandler.getResponse(rpcPackage.getId());
	}

	public void addConnection(IWebSocketConnection connection) {
		this.connection = connection;
	}

	public void removeConnection(IWebSocketConnection connection) {
		this.connection = null;

	}

}
